package service;

import mapper.ApplicationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import po.Application;
import po.ComboboxItem;
import po.Result;

import java.util.ArrayList;
import java.util.List;

@Service
public class ApplicationServiceImpl implements ApplicationService {

    @Autowired
    private ApplicationMapper applicationMapper;

    @Override
    public List<Application> findAllApplications() throws Exception {
        return applicationMapper.findAllApplications();
    }

    @Override
    public Result addApplication(Application application) {
        Result result = new Result();
        try {
            applicationMapper.addApplication(application);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("添加失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("添加成功！");
        return result;
    }

    @Override
    public Result deleteApplicationById(int id) {
        Result result = new Result();
        try {
            applicationMapper.deleteApplicationById(id);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("删除失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("删除成功！");
        return result;
    }

    @Override
    public List<ComboboxItem> findAppForComb() throws Exception {
        List<Application> appList = applicationMapper.findAllApplications();
        List<ComboboxItem> list = new ArrayList<>();
        for (Application app : appList) {
            ComboboxItem item = new ComboboxItem();
            item.setId(app.getId());
            item.setText(app.getName());
            list.add(item);
        }
        return list;
    }

    @Override
    public Result updateApplicationById(int id, Application application) {
        Result result = new Result();
        try {
            application.setId(id);
            applicationMapper.updateApplicationById(application);
        } catch (Exception e) {
            result.setResult("fail");
            result.setMessage("修改失败！");
            return result;
        }
        result.setResult("success");
        result.setMessage("修改成功！");
        return result;
    }
}
